using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

using CSP.SimpleCMS.Data;
using CSP.MembershipInterface.ObjectModel;

namespace CSP.SimpleCMS.DataModel
{
    /// <summary>Manages the operations related with the CaseType</summary>
    public static class CaseTypeDM
    {

        /// <summary>Returns a CaseType with the name sent by parameter</summary>
        /// <param name="name">The name which identifies the CaseType to be found</param>
        /// <returns>A CaseType object</returns>     
        public static CaseType GetCaseTypeByName(string name)
        {
            CaseType caseType = null;

            DataSet dataSet = new DataSet();
            using (DataAccess dataAccess = new DataAccess())
            {
                dataSet = dataAccess.ExecSPReturnDS(DMConstants.SPCaseTypeGET, DMConstants.Fieldname, name);
            }

            if (dataSet != null && dataSet.Tables.Count == 1 && dataSet.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in dataSet.Tables[0].Rows)
                {
                    caseType = ParseRow(row);
                    return caseType;
                }
            }

            return caseType;
        }

        /// <summary>Returns an array with all the CaseType stored in the data source</summary>
        /// <returns>An array of CaseType</returns>  
        public static CaseType[] GetCaseTypes()
        {
            List<CaseType> caseTypes = new List<CaseType>();

            DataSet dataSet = new DataSet();
            using (DataAccess dataAccess = new DataAccess())
            {
                dataSet = dataAccess.ExecSPReturnDS(DMConstants.SPCaseTypeGET, null);
            }

            if (dataSet != null && dataSet.Tables.Count == 1 && dataSet.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in dataSet.Tables[0].Rows)
                {
                    CaseType crmCase = ParseRow(row);
                    caseTypes.Add(crmCase);
                }
            }

            return caseTypes.ToArray();
        }

        /// <summary>Parses a datarow to a CaseType</summary>
        /// <param name="row">The datarow to be parsed</param>
        /// <returns>A CaseType object with the information stored in the datarow</returns>             
        private static CaseType ParseRow(DataRow row)
        {
            CaseType caseType = new CaseType();

            caseType.CaseTypeId = Convert.ToInt16(row[DMConstants.FieldCaseTypeID]);
            caseType.CaseTypeCode = row[DMConstants.FieldCaseTypeCode].ToString();
            caseType.CaseTypeTitle = row[DMConstants.FieldCaseTypeTitle].ToString();

            return caseType;
        }

    }
}
